<template>
  <el-dialog :title="title"  width="600px" append-to-body :visible.sync="dialogedit" @open="openDialog"
    :before-close="closeDialog" :close-on-click-modal="false">
    <div class="form-box">
      <el-form ref="formdata" :model="ruleform" :rules="rules" label-suffix="：" :validate-on-rule-change="false"
        :show-message="false" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="角色名称" prop="role_name"><el-input
                v-model="ruleform.role_name"></el-input></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限字符" prop="role_key">
              <el-input v-model="ruleform.role_key"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="菜单权限">
              <div style="height: 400px;">
                <el-tree class="tree-border" :data="menuOptions" show-checkbox ref="menu" node-key="menu_id"
                   empty-text="加载中，请稍候" :props="defaultProps"
                  style="height: 100%;width: 100%;overflow: auto;"></el-tree>
              </div>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="ruleform.remark"></el-input>

            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="ruleform.status">
                <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value"
                  :label="dict.value">{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="save_validate()">保 存</el-button>
      <el-button @click="closeDialog">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
  import {
    saveRole
  } from '@/api/system/role';
  import {
    treeselect as menuTreeselect,
    roleMenuTreeselect
  } from "@/api/system/menu";
  export default {
    name: 'config_edit',
    dicts: ['sys_normal_disable'],
    props: {
      dialogedit: {
        type: Boolean,
        default: false
      },
      ruleform: {
        type: Object,
        default: () => {
          return {
            role_id: 0,
            role_name: '',
            role_key: '',
            status: 0,
            remark: ''
          };
        }
      }
    },
    data() {
      return {
        title: '修改角色',
        menuOptions: [],
        defaultProps: {
          children: "children",
          label: "menu_name"
        },
        rules: {
          role_name: [{
            required: true,
            message: '角色名称不能为空'
          }],
          status: [{
            required: true,
            message: '状态不能为空'
          }]

        }
      };
    },
    created() {
      this.getMenuTreeselect()
    },
    methods: {
      /** 查询菜单树结构 */
      getMenuTreeselect() {
        menuTreeselect().then(response => {

          this.menuOptions = this.handleTree(response.rows, "menu_id", "parent_id");;
        });
      },
      // 所有菜单节点数据
      getMenuAllCheckedKeys() {
        // 目前被选中的菜单节点
        let checkedKeys = this.$refs.menu.getCheckedKeys();
        // 半选中的菜单节点
        let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
        checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
        return checkedKeys.join(",");
      },
      closeDialog() {
        this.$nextTick(() => {
          this.$refs.formdata.resetFields();
          this.$emit('update:dialogedit', !this.dialogedit);
        });
      },
      save_validate() {
        this.$refs.formdata.validate((valid, valids) => {
          if (valid) {
            this.save_role();
          } else {
            var msg = '';
            for (var key in valids) {
              var item = valids[key];
              msg = item[0].message;
              break;
            }
            if (msg) this.$message.error(msg);

            return false;
          }
        });
      },

      async save_role() {
        const loading = this.loading('保存中...');
        this.ruleform.menuids = this.getMenuAllCheckedKeys();
        saveRole(this.ruleform).then(response => {
          this.$modal.msgSuccess("保存成功");
          loading.close();
          this.closeDialog();
          this.$emit('reload');
        }).catch(err => {
          loading.close();
        });
      },
      async openDialog() {
        this.$nextTick(() => {
          if (this.$refs.menu != undefined) {
            this.$refs.menu.setCheckedKeys([]);
          }
          roleMenuTreeselect(this.ruleform.role_id).then(response => {
            let checkedKeys = response.rows
            checkedKeys.forEach((v) => {
              this.$refs.menu.setChecked(v.menu_id, true, false);
            })
          });

        });


        if (this.ruleform.role_id == 0) {
          this.title = "修改角色";
        } else {
          this.title = "新增角色";
        }
      }
    }
  };
</script>

<style scoped>
  .form-box {
    min-height: 60px;
    padding-right: 10px;
    overflow: auto;
  }
</style>
